給定一個數獨遊戲,解了它!
相信大家都玩過,但還是附一下規則:
class Solution {
public:
bool rule_check(vector<vector<char>>& board, int row, int col){
int correct_count = 0; // there are three rules in Sudoku.
//check row and column. When for-loop finish, only add 2.
for(int i = 0; i < 9; i++){
correct_count += board[i][col] == board[row][col];
correct_count += board[row][i] == board[row][col];
}
int ULC_row = (row/3)*3; // row index of upper left corner in sub-box.
int ULC_col = (col/3)*3; // col index of upper left corner in sub-box.
//check 3x3 sub-box. When for-loop finish, only add 1.
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
correct_count += board[ULC_row + i][ULC_col + j] == board[row][col];
}
}
return correct_count == 3;
}
bool breaktracking(vector<vector<char>>& board, int row, int col){
// should go to the next row?
if(col == 9){
row++;
col = 0;
}
// arrived bottom right corner?
if(row == 9){
return true; //done
}
// Is the cell empty?
// true: find appropriate value, false: go to the next cell.
if(board[row][col]=='.'){
//test all of possibility
for(int val = 1; val < 10; val++){
board[row][col] = '0' + val;
// check and recursion.
if(rule_check(board, row, col) && breaktracking(board, row, col + 1)){
return true;
}
//the val is invalid, so reset.
board[row][col] = '.';
}
}
else{
return breaktracking(board, row, col + 1);
}
return false;
}
void solveSudoku(vector<vector<char>>& board) {
breaktracking(board, 0, 0);
}
};
visited_row[9][9]
visited_col[9][9]
visited_sub_box[3][3][9]
class Solution {
public:
bool visited_row[9][9] = {false};
bool visited_col[9][9] = {false};
bool visited_sub_box[3][3][9] = {false};
bool rule_check(int row, int col, int val){
return !visited_row[row][val] && !visited_col[col][val] && !visited_sub_box[row/3][col/3][val];
}
bool breaktracking(vector<vector<char>>& board, int row, int col) {
// should go to the next row?
if(col == 9){
row++;
col = 0;
}
// arrived bottom right corner?
if(row == 9){
return true; //done
}
// Is the cell empty?
// true: find appropriate value, false: check next cells
if(board[row][col]=='.'){
//test all of possibility
for(int val = 0; val < 9; val++){
// check
if(rule_check(row, col, val)) {
visited_row[row][val] = true;
visited_col[col][val] = true;
visited_sub_box[row/3][col/3][val] = true;
board[row][col] = '1' + val;
//recursive
if(breaktracking(board, row, col + 1)){
return true;
}
//the val is invalid, so reset.
board[row][col] = '.';
visited_row[row][val] = false;
visited_col[col][val] = false;
visited_sub_box[row/3][col/3][val] = false;
}
}
}
else{
return breaktracking(board, row, col + 1);
}
return false;
}
void solveSudoku(vector<vector<char>>& board) {
//init
int q_val = 0;
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9; j++){
if(isdigit(board[i][j])){
q_val = board[i][j] - '1';
visited_row[i][q_val] = true;
visited_col[j][q_val] = true;
visited_sub_box[i/3][j/3][q_val] = true;
}
}
}
breaktracking(board, 0, 0);
}
};